package com.qf.controller;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.pojo.SmsInterfaceForm;
import com.qf.service.SmsInterfaceService;
import com.qf.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Zwnan
 */
@RestController
@RequestMapping("/sms")
public class InterfaceController {

    @Value("${ip-header}")
    private List<String> ipHeaders;
    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private SmsInterfaceService smsInterfaceService;


    @PostMapping("/interface")
    public Map smsInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest req){

        String reallyIpAddress = this.getReallyIpAddress(req);
        smsInterfaceForm.setIp(reallyIpAddress);

        String clientID = smsInterfaceForm.getClientID();
        Map map = cacheFeign.hMap(CacheConstants.CACHE_PREFIX_CLIENT+clientID);
        if (null == map || map.size() ==0){
            return Result.error(101,"认证错：clientId错误");
        }

        String mobile = smsInterfaceForm.getMobile();
        if (StringUtils.isEmpty(mobile)){
            return Result.error(105,"手机号错误");
        }
        String[] ms = mobile.split(",");
        if (ms.length> 100){
            return Result.error(105,"手机号错误，最多100个");
        }
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        Set<String> errorSet = new HashSet<>();
        for (String m : ms) {
            if (!m.matches(regex)){
                errorSet.add(m);
            }
        }
        if (errorSet.size()>0){
            return Result.error(105,"手机号错误"+errorSet);
        }

        String pwd = smsInterfaceForm.getPwd();
        if (StringUtils.isEmpty(pwd)){
            return Result.error(102,"密码错误");
        }
        if (!pwd.equals(map.get("pwd"))){
            return Result.error(102,"密码错误");
        }
        String content = smsInterfaceForm.getContent();
        if (StringUtils.isEmpty(content)){
            return Result.error(104,"必须有短信的内容");
        }
        if (content.length()>500){
            return Result.error(104,"消息长度错误");
        }

        String srcID = smsInterfaceForm.getSrcID();
        if (StringUtils.isEmpty(srcID)){
            return Result.error(106,"下行编号（srcID）错误");
        }

        String ip = smsInterfaceForm.getIp();
        if (!ip.equals(map.get("ipaddress"))){
            return Result.error(103,"IP校验错误");
        }

        smsInterfaceService.sendMessage(smsInterfaceForm);

        return Result.error(0,"成功");
    }
    private String getReallyIpAddress(HttpServletRequest req){

        for (String ipHeader : ipHeaders) {
            if (!StringUtils.isEmpty(ipHeader)&&ipHeader.length()>0){
                String ip = req.getHeader(ipHeader);
                if (!StringUtils.isEmpty(ip)&&"unknown".equalsIgnoreCase(ip)){
                    return ip;
                }
            }
        }
        return req.getRemoteAddr();

    }

}
